from elasticsearch import Elasticsearch
import pandas as pd

def ExportEsData(excel_path):
    # 连接es集群
    es = Elasticsearch(
        ["192.168.2.110"],
        http_auth=('elastic', 'xxxxxxx'),
        port=9200)

    # 指定数据查询DSL
    body = {
            "query": {
                "match_all": {}
            },
            "sort": [
                {
                "seq": {
                    "order": "desc"
                }
                }
            ],
            "from":0,
            "size": 200
            }

    # 获取数据
    query = es.search(index='wechat',
                      doc_type='_doc',
                      size=200,
                      body=body)

    results = query['hits']['hits']

    # 将 _source 对应的value提出来保存至列表
    list_dic = []
    for dic in results:
        dic.update(dic['_source'])
        del dic['_source']
        list_dic.append(dic)

    # 保存至excel
    EsData = pd.DataFrame(list_dic, index=[i for i in range(len(list_dic))])
    EsData.to_excel(excel_path, index=False)

if __name__ == "__main__":
    excel_path='/tmp/b.xlsx'
    ExportEsData(excel_path)
